<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    <img src="" alt="" id="pic">
  </div>
  <div>
    <input type="file" id="file">
  </div>


  <script>
    const fileDom = document.querySelector('#file')
    // 监听文件域表单项改变事件，如果有改变则触发，从而得到一个File对象
    fileDom.onchange = function () {
      // 文件对象
      const file = fileDom.files[0];
      // html5提供一个api
      const fileReader = new FileReader()
      // 把得到的File对象转为流  stream可以通过ajax发送
      fileReader.readAsArrayBuffer(file)
      fileReader.onloadend = function () {
        const xhr = new XMLHttpRequest;
        xhr.open('POST', '/upload', true);
        xhr.setRequestHeader('filename', file.name)
        xhr.send(fileReader.result)
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            let json = eval('(' + xhr.responseText + ')')
            pic.src = json.url
          }
        }
      }
    }

  </script>
</body>

</html>